<template>
  <div class="comment-management">
    <el-card shadow="hover" class="comments-card">
      <!-- 搜索和过滤组件 -->
      <div class="filter-bar">
        <el-input
          v-model="commentKeyword"
          placeholder="搜索评论内容"
          class="search-input"
          clearable
          @keyup.enter="getComments"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-button type="primary" @click="getComments" style="margin-left: 10px;">
          <el-icon><Search /></el-icon>查询
        </el-button>
      </div>
      
      <!-- 评论列表 -->
      <el-table
        v-loading="loading"
        :data="comments"
        style="width: 100%; margin-top: 20px;"
        border
        @selection-change="handleCommentSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="内容" min-width="280" show-overflow-tooltip />
        <el-table-column prop="answerContent" label="评论回答" min-width="180" show-overflow-tooltip />
        <el-table-column prop="questionTitle" label="所属问题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="userName" label="评论者" width="120" />
        <el-table-column prop="createTime" label="评论时间" width="180" />
        <el-table-column label="操作" fixed="right" width="170">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click="navigateToQuestion(scope.row.questionId, scope.row.answerId)"
            >查看</el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="deleteComment(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作 -->
      <CommentBatchActions
        v-if="selectedComments.length > 0"
        :count="selectedComments.length"
        @batch-delete="batchDeleteComments"
      />
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { 
  getComments as apiGetComments,
  deleteComment as apiDeleteComment,
  batchDeleteComments as apiBatchDeleteComments
} from '../../api/admin';
import CommentBatchActions from './CommentBatchActions.vue';

const props = defineProps({});
const emit = defineEmits(['refresh']);
const router = useRouter();

// 评论管理相关
const comments = ref([]);
const commentKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedComments = ref([]);
const loading = ref(false);

// 获取评论列表
const getComments = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      keyword: commentKeyword.value
    };
    
    const response = await apiGetComments(params);
    if (response.code === 200) {
      comments.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取评论列表失败');
    }
  } catch (error) {
    console.error('获取评论列表失败:', error);
    ElMessage.error('获取评论列表失败: ' + (error.message || '未知错误'));
    comments.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 处理评论选择变化
const handleCommentSelectionChange = (selection) => {
  selectedComments.value = selection;
};

// 处理评论分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getComments();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getComments();
};

// 删除评论
const deleteComment = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此评论吗？此操作不可恢复!', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    });
    
    loading.value = true;
    const response = await apiDeleteComment(id);
    if (response.code === 200) {
      ElMessage.success('评论已删除');
      getComments();
    } else {
      ElMessage.error(response.message || '删除评论失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除评论
const batchDeleteComments = async () => {
  if (selectedComments.value.length === 0) {
    ElMessage.warning('请选择要删除的评论');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedComments.value.length}个评论吗？此操作不可恢复！`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    });
    
    const commentIds = selectedComments.value.map(comment => comment.id);
    const response = await apiBatchDeleteComments(commentIds);
    
    if (response.code === 200) {
      ElMessage.success(`已删除${response.data || selectedComments.value.length}个评论`);
      getComments();
    } else {
      ElMessage.error(response.message || '批量删除评论失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除评论失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  }
};

// 导航到问题详情页并定位到回答
const navigateToQuestion = (questionId, answerId) => {
  if (!questionId) {
    ElMessage.warning('问题ID不存在，无法跳转');
    return;
  }
  
  try {
    // 使用路由跳转
    router.push({
      path: `/question/${questionId}`,
      query: answerId ? { answerId } : {}
    });
  } catch (error) {
    console.error('页面跳转失败:', error);
    ElMessage.error('页面跳转失败');
  }
};

// 初始化
onMounted(() => {
  getComments();
});

// 暴露方法给父组件
defineExpose({
  getComments
});
</script>

<style scoped>
.comment-management {
  width: 100%;
}

.comments-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-bar .el-button {
    width: 100%;
    margin-left: 0 !important;
  }
}
</style> 